<template>
  <div id="line-chart"  :class="className" :style="{ height:height, width:width }" />
</template>
<script setup lang="ts">
import { onMounted, onUnmounted, PropType, ref, watch } from 'vue';
import * as echarts from 'echarts'
import resize from '@/utils/resize'

export interface LineChartData {
  expectedData: number[]
  actualData: number[]
}
const { chart, mounted, beforeDestory  } = resize()
let echart = echarts

const props = defineProps({
  chartData: {
    type: Object as PropType<LineChartData>,
    required: true
  },
  className: {
    type: String,
    default: 'chart'
  },
  width: {
    type: String,
    default: '100%'
  },
  height: {
    type: String,
    default: '350px'
  },
  autoResize: {
    type: Boolean,
    default: true
  },
})

watch( () => props.chartData,
  val => {
    initChart()
  },
)

// 初始化echarts
const initChart = () => {
  if (chart.value) {
    chart.value.setOption({
      xAxis: {
        data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'],
        boundaryGap: false,
        axisTick: {
          show: false
        }
      },
      grid: {
        left: 10,
        right: 10,
        bottom: 20,
        top: 30,
        containLabel: true
      },
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'cross'
        },
        padding: [5, 10]
      },
      yAxis: {
        axisTick: {
          show: false
        }
      },
      legend: {
        data: ['expected', 'actual']
      },
      series: [
        {
          name: 'expected',
          itemStyle: {
            color: '#FF005A',
          },
          smooth: true,
          type: 'line',
          data: props.chartData.expectedData,
          lineStyle: {
            color: '#FF005A',
            width: 2
          },
          animationDuration: 2800,
          animationEasing: 'cubicInOut'
        },
        {
          name: 'actual',
          smooth: true,
          type: 'line',
          itemStyle: {
            color: '#3888fa',
            areaStyle: {
              color: '#f3f8ff'
            }
          },
          lineStyle: {
            color: '#3888fa',
            width: 2
          },
          data: props.chartData.actualData,
          animationDuration: 2800,
          animationEasing: 'quadraticOut'
        }
      ]
    })
  }
}

onMounted(() => {
  chart.value = echart.init(document.getElementById('line-chart') as HTMLDivElement, 'macarons')
  initChart()
  mounted()
})
onUnmounted(() => {
  beforeDestory()
  chart.value.dispose()
})
</script>